package com.kancy.vip.pattern.singleton.hunger;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class HungerSingleton implements Serializable{
    /**
     * 类加载时初始化对象，多线程情况下，也是线程安全的。
     * 缺点：
     *      当使用不到改单例时，会浪费额外的内存空间
     * */
    private static final HungerSingleton hunger = new HungerSingleton();
    private HungerSingleton(){
        //防止反射入侵
        if(hunger != null){
            throw new RuntimeException("防止反射入侵");
        }
        System.out.println("HungerSingleton 正常初始化...");
    }

    /**
     * 防止序列化破坏
     * readResolveMethod = getInheritableMethod(cl, "readResolve", null, Object.class);
     */
    private Object readResolve(){
        return hunger;
    }

    /**
     * 反序列化拦截
     * readObjectMethod = getPrivateMethod(cl, "readObject",
     *                            new Class<?>[] { ObjectInputStream.class },
     *                            Void.TYPE);
     * @param inputStream
     */
    private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
        inputStream.defaultReadObject();
        // 读取其他内容
        Object object = inputStream.readObject();
        System.out.println("自定义读："+object);
    }
    private void writeObject(ObjectOutputStream outputStream) throws IOException, ClassNotFoundException {
        outputStream.defaultWriteObject();
        // 可以实现 transient 修饰的 字段也会被序列化
        outputStream.writeObject("good");
    }

    public static HungerSingleton getInstance(){
        return hunger;
    }
}
